package psn.kiko.config.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import psn.kiko.pojo.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 全局异常处理器<br> 程序的其它地方不需要再处理异常，只需要直接抛出异常
 */
@ControllerAdvice(basePackages = "psn.kiko.controller")
@ResponseBody
@Slf4j
public class GlobalExceptionHandler{
	
	//拦截非自定义的异常
	@ExceptionHandler(value = {Exception.class})
	public R handleNoneBusinessException(Exception exception){
		if(log.isDebugEnabled()){
			log.error("开始处理非自定义异常:{} : {}",exception.getClass().getName(),exception.getMessage());
		}
		StackTraceElement[] stackTrace = exception.getStackTrace();
		ArrayList<String> exceptionStackTrace = new ArrayList<>(stackTrace.length);
		for(StackTraceElement te: stackTrace){
			exceptionStackTrace.add("at "+te.getLineNumber()+" line in "+te.getFileName());
		}
		HashMap<String,List<String>> data = new HashMap<>();
		data.put("exceptionStackTrace", exceptionStackTrace);
		return R.failWithMsgAndData(exception.getMessage(),data);
	}
}
